<!-- 商品分类 -->
<template>
  <div id="cLASS">
    <div class="box">
      <div class="box_header">
        <div>商品分类</div>
        <div><el-button type="primary" @click="handleAdd">添加分类</el-button></div>
      </div>
      <!-- 列表 -->
      <el-table :data="currentOrders" style="width: 100%">
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="cateName" label="分类" width="250">
          <!-- default不要拼错，不然元素不显示 -->
          <template #default="scoped">
            <div v-show="!scoped.row.inpState">{{ scoped.row.cateName }}</div>
            <div v-show="scoped.row.inpState"><input type="text" v-model="inpNameEdit"></div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="是否启用">
          <template #default="scoped">
            <el-switch class="ml-2 switchAll" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              :disabled="isDisabled" @change="handleSwitchChange(scoped.row.id, $event)" v-model="scoped.row.state"
              :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #default="scoped">
            <el-button @click="handleEdit(scoped.row.id)" v-show="!scoped.row.inpState">编辑</el-button>
            <el-button @click="handleFinish(scoped.row.id)" type="success" v-show="scoped.row.inpState">完成</el-button>
            <el-button type="danger" @click="open(scoped.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 翻页 -->
      <div class="pageBox">
        <div class="demo-pagination-block">
          <!-- <div class="demonstration">All combined</div> -->
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5]" :size="size"
            layout="total, sizes, prev, pager, next, jumper" :total="classList.length" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" class="pageBox_use" />
        </div>
        <!-- 添加分类盒子 -->
        <div class="addBox" v-show="addMsg">
          <div class="addBox_header">
            <div>添加商品分类</div>
            <div @click="handleCanel">X</div>
          </div>
          <div class="addBox_body">
            <div>
              <span>分类名称</span>
              &nbsp;
              <el-input v-model="addInputValue" style="width: 38vw;height: 2.5vw;font-size: 1vw;" />
            </div>
            <div>
              是否启用
              &nbsp;
              <el-switch v-model="valueOpenOrClose" class="ml-2"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;width: 5vw;height: 1vw;" />
            </div>
            <br>
            <div class="sure">
              <el-button @click="handleCanel">取消</el-button>
              <el-button type="primary" @click="sureAdd">确定</el-button>
            </div>
          </div>
        </div>
        <!-- 蒙版 -->
        <div class="mask" v-show="addMsg"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { fetchLoginNine } from '../../api/index';
import { fetchLoginEve } from '../../api/index';
import { fetchLoginTwi } from '../../api/index';
import { fetchLoginthirteen } from '../../api/index';
import { ComponentSize } from 'element-plus';

//引入弹框类型
import { ElMessage, ElMessageBox } from 'element-plus'
//引入删除弹框以及删除操作
const open = (id: any) => {
  ElMessageBox.confirm(
    '是否删除该商品?',
    '警告',
    {
      confirmButtonText: '是的',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      //console.log(id);
      //const index = tableList.value.findIndex((item) => item.id === id)
      //console.log(index);
      const userInfo = ref({
        id: id,
      })
      const res = await fetchLoginTwi(userInfo.value);
      console.log(res);//删除成功
      location.reload();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

//翻页联动列表
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref<ComponentSize>('default')

//表格数据绑定翻页
const currentOrders = computed(() => {
  return classList.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
//数组列表
const classList = ref([]);
//获取分类
onMounted(async () => {
  const res = await fetchLoginNine({ currentPage: 1, pageSize: 99 });
  //console.log(res);
  // res.data.data.forEach(item => {
  //     const state = localStorage.getItem(`switchState-${item.id}`);
  //     item.state = state === 'true'?true:false; // 如果 session 中有值，则使用该值，否则默认为 false
  //     if (item.state === undefined) { // 如果没有从 session 中读取到值，则默认为 true
  //         item.state = true;
  //     }
  // });
  classList.value = res.data.data;
});

//监听 scoped.row.state 的变化
function handleSwitchChange(id, newValue) {
  // 这里的 newValue 就是开关的新状态
  //console.log(`分类 ${id} 的开关状态改变为 ${newValue}`);
  // 在这里可以执行你想要的操作
  switchNow.value = newValue;
  //console.log(switchNow.value);
}


//修改
const isDisabled = ref(true);
function handleEdit(id: any) {
  const index = classList.value.findIndex((item) => item.id === id)
  //console.log(index);
  classList.value[index].inpState = !classList.value[index].inpState;
  isDisabled.value = !isDisabled.value;
}

//完成修改
const inpNameEdit = ref('');//修改的名字的参数
const switchNow = ref();//开关状态，联动监听
const handleFinish = async (id: number) => {
  const index = classList.value.findIndex((item) => item.id === id)
  //console.log(index);
  classList.value[index].inpState = !classList.value[index].inpState;
  isDisabled.value = !isDisabled.value;

  interface IUserInfo {
    id: number,
    cateName: string,
    state: Boolean,
  }

  const userInfo = ref<IUserInfo>({
    id: id,
    cateName: inpNameEdit.value,
    state: switchNow.value === 1 ? true : false,
  })

  //console.log(userInfo.value); // 打印查看参数是否正确

  const res = await fetchLoginEve(userInfo.value);
  //console.log(res);
}

//添加分类
const valueOpenOrClose = ref(false);
const addInputValue = ref('');
const addMsg = ref(false);

const handleAdd = async () => {
  addMsg.value = !addMsg.value;
}

function handleCanel() {
  addMsg.value = !addMsg.value;
}

const sureAdd = async () => {
  interface IUserInfo {
    cateName: string,
    state: Boolean,
  }

  const userInfo = ref<IUserInfo>({
    cateName: addInputValue.value,
    state: valueOpenOrClose.value,
  })

  const res = await fetchLoginthirteen(userInfo.value);
  //console.log(res);
  location.reload();
}

//switch反转 -- 以及成功突破组件的局限性问题，在组件上使用change事件并在此点击事件进行修改并更新onMounted中的数据
// function handleReversal(id, newState) {
//     const index = classList.value.findIndex((item) => item.id === id);
//     classList.value[index].state = newState;
//     localStorage.setItem(`switchState-${id}`, newState);
//     //console.log(classList.value[index].state);
// }


</script>

<style scoped>
.box {
  width: 85vw;
  margin-left: 1vw;
  box-shadow: 0.1vw 0.1vw 0.1vw 0.1vw #f0f0f0;
}

.box_header {
  padding: 1vw;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
}

.addBox {
  width: 50vw;
  height: 15vw;
  z-index: 9999;
  border: 1px solid black;
  position: absolute;
  top: 10vw;
  left: 28vw;
  font-size: 1vw;
  background-color: #fff;
  padding: 2vw;

  >.addBox_header {
    display: flex;
    justify-content: space-between;

    >div:nth-child(2) {
      cursor: pointer;
    }
  }

  >.addBox_body {
    margin-top: 1vw;

    >div {
      margin: 2vw;
    }
  }
}

.mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 8888;
  background-color: rgba(0, 0, 0, 0.5);
}

.sure {
  width: 20vw;
  height: 5vw;
  font-size: 0.9vw;
  position: relative;
  left: 40vw;
}

.pageBox {
  padding: 1vw;
}
</style>